package com.grj.parkingsystem.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.grj.parkingsystem.common.JwtUtil;
import com.grj.parkingsystem.entity.User;
import com.grj.parkingsystem.entity.Vehicle;
import com.grj.parkingsystem.mapper.UserMapper;
import com.grj.parkingsystem.service.SystemConfigService;
import com.grj.parkingsystem.service.UserService;
import com.grj.parkingsystem.service.VehicleService;
import com.grj.parkingsystem.mapper.VehicleMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
* @author ganru
* @description 针对表【t_vehicle(用户车辆表)】的数据库操作Service实现
* @createDate 2025-05-16 16:51:44
*/
@Service
public class VehicleServiceImpl extends ServiceImpl<VehicleMapper, Vehicle>
    implements VehicleService{

    @Resource
    private SystemConfigService systemConfigService;

    @Resource
    private UserMapper userMapper;

    @Resource
    private JwtUtil jwtUtil;

    @Override
    public List<Vehicle> getVehicles(String token) {
        // 解析Token
        String username = jwtUtil.getUsernameFromToken(token);
        User user = userMapper.selectOne(new QueryWrapper<User>().eq("username", username));

        return baseMapper.selectList(new QueryWrapper<Vehicle>().eq("user_id", user.getId()));
    }

    @Override
    @Transactional
    public boolean bindVehicle(String token, String licensePlate, String vehicleType, String color) {
        // 解析Token
        String username = jwtUtil.getUsernameFromToken(token);
        User user = userMapper.selectOne(new QueryWrapper<User>().eq("username", username));
        // 检查是否已绑定
        int count = Math.toIntExact(baseMapper.selectCount(new QueryWrapper<Vehicle>()
                .eq("user_id", user.getId())
                .eq("license_plate", licensePlate)));
        if (count > 0) {
            return false;
        }

        // 检查是否超过最大绑定数量
        int maxVehicles = Integer.parseInt(systemConfigService.getConfigValue("max_bind_vehicles"));
        int currentCount = Math.toIntExact(baseMapper.selectCount(new QueryWrapper<Vehicle>().eq("user_id", user.getId())));
        if (currentCount >= maxVehicles) {
            return false;
        }

        Vehicle vehicle = new Vehicle();
        vehicle.setUserId(user.getId());
        vehicle.setLicensePlate(licensePlate);
        vehicle.setVehicleType(vehicleType);
        vehicle.setColor(color);
        vehicle.setBindTime(new Date());
        vehicle.setStatus(1);

        // 如果是第一个绑定的车辆，设为默认
        if (currentCount == 0) {
            vehicle.setIsDefault(1);
        } else {
            vehicle.setIsDefault(0);
        }

        return save(vehicle);
    }

    @Override
    @Transactional
    public boolean unbindVehicle(String token, Long vehicleId) {
        // 解析Token
        String username = jwtUtil.getUsernameFromToken(token);
        User user = userMapper.selectOne(new QueryWrapper<User>().eq("username", username));

        Vehicle vehicle = baseMapper.selectOne(new QueryWrapper<Vehicle>()
                .eq("user_id", user.getId())
                .eq("id", vehicleId));
        if (vehicle == null) {
            return false;
        }

        // 如果解绑的是默认车辆，需要重新设置默认
        if (vehicle.getIsDefault().equals(1)) {
            Vehicle newDefault = baseMapper.selectOne(new QueryWrapper<Vehicle>()
                    .eq("user_id", user.getId())
                    .ne("id", vehicleId)
                    .last("LIMIT 1"));
            if (newDefault != null) {
                newDefault.setIsDefault(0);
                baseMapper.updateById(newDefault);
            }
        }

        return removeById(vehicleId);
    }


    @Override
    @Transactional
    public boolean setDefaultVehicle(String token, Long vehicleId) {

        // 解析Token
        String username = jwtUtil.getUsernameFromToken(token);
        User user = userMapper.selectOne(new QueryWrapper<User>().eq("username", username));

        // 先将所有车辆设为非默认
        baseMapper.update(null, new UpdateWrapper<Vehicle>()
                .eq("user_id", user.getId())
                .set("is_default", false));

        // 再将指定车辆设为默认
        Vehicle vehicle = new Vehicle();
        vehicle.setId(vehicleId);
        vehicle.setIsDefault(1);
        return updateById(vehicle);
    }
}




